<template>
  <div class="login-container">
    <div class="login-wrapper">
      <!-- 左侧品牌展示区（仅PC端显示） -->
      <div class="brand-section">
        <div class="brand-content">
          <h1 class="brand-title">医联智导</h1>
          <p class="brand-slogan">智能导诊，让就医更简单</p>
          <div class="brand-image">
            <svg width="200" height="200" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="12" cy="6" r="4" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M8.5 18c0-2.5 1-4.5 2.5-5.5c1.5-1 3.5-1 6 0l0 0c2 1 3 3 3 5.5" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M16 21v-3.5c0-1-.5-2-1.5-2.5s-2 .5-3 1.5c-1-1-1.5-1.5-3-1.5s-1.5 1.5-1.5 2.5v3.5" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M6 13c0-1 1-2 2-2s2 1 2 2" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M16 13c0-1-1-2-2-2s-2 1-2 2" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
        </div>
      </div>
      
      <!-- 右侧登录表单 -->
      <div class="form-section">
        <div class="form-content">
          <div class="form-header">
            <h2>登录</h2>
            <p>欢迎使用医联智导平台</p>
          </div>
          
          <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
            <!-- 手机号输入 -->
            <el-form-item prop="phone">
              <el-input
                v-model="loginForm.phone"
                placeholder="请输入手机号"
                :prefix-icon="Phone"
                :disabled="isLoading"
                clearable
              />
            </el-form-item>
            
            <!-- 密码输入 -->
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                :show-password="showPassword"
                @click:prefix="handlePrefixClick"
                :disabled="isLoading"
                clearable
              />
            </el-form-item>
            
            <!-- 验证码登录切换 -->
            <div class="form-options">
              <el-checkbox v-model="useCodeLogin" @change="handleLoginTypeChange">验证码登录</el-checkbox>
              <el-link type="primary" @click="goToRegister">立即注册</el-link>
            </div>
            
            <!-- 验证码输入（仅在验证码登录模式下显示） -->
            <el-form-item prop="code" v-if="useCodeLogin">
              <el-input
                v-model="loginForm.code"
                placeholder="请输入验证码"
                :prefix-icon="Message"
                :disabled="isLoading || countdown > 0"
                clearable
              >
                <template #suffix>
                  <el-button
                    :disabled="!loginForm.phone || isLoading || countdown > 0"
                    type="text"
                    @click="getVerificationCode"
                    class="get-code-btn"
                  >
                    {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            
            <!-- 记住我和忘记密码 -->
            <div class="form-options" v-if="!useCodeLogin">
              <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
              <el-link type="primary" @click="handleForgotPassword">忘记密码？</el-link>
            </div>
            
            <!-- 错误提示 -->
            <div v-if="error" class="error-message">
              <el-icon><Warning /></el-icon>
              <span>{{ error }}</span>
            </div>
            
            <!-- 登录按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                class="login-btn"
                :loading="isLoading"
                @click="handleLogin"
                :disabled="isLoading"
              >
                登录
              </el-button>
            </el-form-item>
            
            <!-- 第三方登录 -->
            <div class="third-party-login">
              <div class="divider">
                <span>其他登录方式</span>
              </div>
              <div class="third-party-buttons">
                <el-button
                  type="default"
                  circle
                  @click="handleWechatLogin"
                />
                <el-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16"></svg></el-icon>
              </div>
            </div>
          </el-form>
        </div>
      </div>
    </div>
    
    <!-- 忘记密码弹窗 -->
    <el-dialog v-model="forgotPasswordVisible" title="忘记密码" width="400px">
      <el-form ref="forgotFormRef" :model="forgotForm" :rules="forgotRules">
        <el-form-item prop="phone">
          <el-input
            v-model="forgotForm.phone"
            placeholder="请输入手机号"
            :prefix-icon="Phone"
            clearable
          />
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="forgotForm.code"
            placeholder="请输入验证码"
            :prefix-icon="Message"
            :disabled="forgotCountdown > 0"
            clearable
          >
            <template #suffix>
              <el-button
                :disabled="!forgotForm.phone || forgotCountdown > 0"
                type="text"
                @click="getForgotVerificationCode"
              >
                {{ forgotCountdown > 0 ? `${forgotCountdown}秒后重试` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
            v-model="forgotForm.newPassword"
            type="password"
            placeholder="请设置新密码"
            :prefix-icon="Lock"
            :show-password="showForgotPassword"
            @click:prefix="handleForgotPrefixClick"
            clearable
          />
          <div v-if="passwordStrength > 0" class="password-strength">
            <div class="strength-indicators">
              <div
                v-for="(level, index) in 3"
                :key="index"
                class="strength-indicator"
                :class="{
                  'weak': passwordStrength >= 1 && level === 1,
                  'medium': passwordStrength >= 2 && level === 2,
                  'strong': passwordStrength >= 3 && level === 3
                }"
              />
            </div>
            <span class="strength-text">
              {{ passwordStrengthText }}
            </span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="forgotPasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="handleResetPassword">确认重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElForm, ElFormItem, ElInput, ElButton, ElCheckbox, ElLink, ElDialog, ElMessage, ElIcon } from 'element-plus'
import { Phone, Lock, Message, Warning } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loginFormRef = ref(null)
const loginForm = reactive({
  phone: '',
  password: '',
  code: '',
  remember: false
})
const useCodeLogin = ref(false)
const showPassword = ref(false)
const countdown = ref(0)
const isLoading = computed(() => authStore.isLoading)
const error = computed(() => authStore.error)

// 忘记密码相关
const forgotPasswordVisible = ref(false)
const forgotFormRef = ref(null)
const forgotForm = reactive({
  phone: '',
  code: '',
  newPassword: ''
})
const showForgotPassword = ref(false)
const forgotCountdown = ref(0)
const passwordStrength = ref(0)
const passwordStrengthText = computed(() => {
  switch (passwordStrength.value) {
    case 1: return '弱'
    case 2: return '中'
    case 3: return '强'
    default: return ''
  }
})

// 表单验证规则
const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20位之间', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
}

const forgotRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请设置新密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度应在8-20位之间', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    
    if (useCodeLogin.value) {
      // 验证码登录逻辑
      // 在实际项目中，这里应该调用专门的验证码登录API
      await authStore.login(loginForm.phone, loginForm.code, loginForm.remember)
    } else {
      // 密码登录逻辑
      await authStore.login(loginForm.phone, loginForm.password, loginForm.remember)
    }
    
    ElMessage.success('登录成功')
    
    // 获取重定向地址，如果没有则跳转到首页
    const redirect = router.currentRoute.value.query.redirect || '/'
    router.push(redirect)
  } catch (err) {
    // 验证失败或登录失败
    console.error('登录失败:', err)
    ElMessage.error('登录失败，请检查账号密码')
  }
}

// 切换登录方式
const handleLoginTypeChange = () => {
  // 重置表单
  loginForm.code = ''
  countdown.value = 0
}

// 获取验证码
const getVerificationCode = async () => {
  try {
    // 验证手机号
    if (!loginForm.phone || !/^1[3-9]\d{9}$/.test(loginForm.phone)) {
      ElMessage.error('请输入正确的手机号')
      return
    }
    
    await authStore.getVerificationCode(loginForm.phone)
    ElMessage.success('验证码发送成功')
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (err) {
    console.error('发送验证码失败:', err)
    ElMessage.error('发送验证码失败，请重试')
  }
}

// 微信登录
const handleWechatLogin = () => {
  ElMessage.info('微信登录功能开发中')
}

// 前往注册页面
const goToRegister = () => {
  router.push('/register')
}

// 显示忘记密码弹窗
const handleForgotPassword = () => {
  forgotPasswordVisible.value = true
}

// 获取忘记密码验证码
const getForgotVerificationCode = async () => {
  try {
    // 验证手机号
    if (!forgotForm.phone || !/^1[3-9]\d{9}$/.test(forgotForm.phone)) {
      ElMessage.error('请输入正确的手机号')
      return
    }
    
    await authStore.getVerificationCode(forgotForm.phone)
    ElMessage.success('验证码发送成功')
    
    // 开始倒计时
    forgotCountdown.value = 60
    const timer = setInterval(() => {
      forgotCountdown.value--
      if (forgotCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (err) {
    console.error('发送验证码失败:', err)
    ElMessage.error('发送验证码失败，请重试')
  }
}

// 重置密码
const handleResetPassword = async () => {
  try {
    await forgotFormRef.value.validate()
    
    await authStore.resetPassword(forgotForm.phone, forgotForm.code, forgotForm.newPassword)
    ElMessage.success('密码重置成功')
    
    // 关闭弹窗
    forgotPasswordVisible.value = false
    
    // 清空表单
    forgotForm.phone = ''
    forgotForm.code = ''
    forgotForm.newPassword = ''
    passwordStrength.value = 0
  } catch (err) {
    console.error('重置密码失败:', err)
    ElMessage.error('重置密码失败，请重试')
  }
}

// 处理密码强度检测
const handlePasswordInput = (value) => {
  let strength = 0
  
  // 长度检查
  if (value.length >= 8) strength++
  
  // 包含字母检查
  if (/[A-Za-z]/.test(value)) strength++
  
  // 包含数字检查
  if (/\d/.test(value)) strength++
  
  passwordStrength.value = strength
}

// 显示/隐藏密码
const handlePrefixClick = () => {
  showPassword.value = !showPassword.value
}

const handleForgotPrefixClick = () => {
  showForgotPassword.value = !showForgotPassword.value
}

// 监听密码输入变化
const watchPassword = () => {
  // 监听忘记密码的新密码输入
  const unwatch = computed(() => forgotForm.newPassword)
  const unwatchEffect = () => {
    handlePasswordInput(forgotForm.newPassword)
  }
  
  // 在Vue 3中，你可以使用watchEffect来监听响应式数据的变化
  // 这里为了简化，使用setTimeout模拟
  const interval = setInterval(() => {
    handlePasswordInput(forgotForm.newPassword)
  }, 300)
  
  // 组件卸载时清除定时器
  return () => {
    clearInterval(interval)
  }
}

// 生命周期钩子
onMounted(() => {
  // 自动聚焦到手机号输入框
  nextTick(() => {
    const phoneInput = document.querySelector('input[placeholder="请输入手机号"]')
    if (phoneInput) {
      phoneInput.focus()
    }
  })
  
  // 开始监听密码强度
  const cleanup = watchPassword()
  
  // 组件卸载时清理
  return cleanup
})
</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-wrapper {
  display: flex;
  width: 100%;
  max-width: 1000px;
  background-color: #ffffff;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 左侧品牌展示区 */
.brand-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1989fa 0%, #36cbcb 100%);
  padding: 60px;
  color: #ffffff;
  display: none;
}

/* PC端显示品牌区 */
@media (min-width: 768px) {
  .brand-section {
    display: flex;
  }
}

.brand-content {
  text-align: center;
}

.brand-title {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 16px;
}

.brand-slogan {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 40px;
}

.brand-image {
  margin-top: 20px;
}

/* 右侧表单区 */
.form-section {
  flex: 1;
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-content {
  width: 100%;
  max-width: 350px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
}

.form-header p {
  color: #606266;
  font-size: 14px;
}

.login-form {
  width: 100%;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
  font-size: 16px;
  padding: 10px;
}

.error-message {
  display: flex;
  align-items: center;
  color: #f56c6c;
  font-size: 13px;
  margin-bottom: 15px;
  padding: 8px 12px;
  background-color: #fef0f0;
  border-radius: 4px;
}

.error-message .el-icon {
  margin-right: 8px;
}

/* 第三方登录 */
.third-party-login {
  margin-top: 30px;
}

.divider {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background-color: #e4e7ed;
}

.divider span {
  padding: 0 20px;
  color: #909399;
  font-size: 14px;
}

.third-party-buttons {
  display: flex;
  justify-content: center;
}

.third-party-buttons .el-button {
  font-size: 24px;
  color: #36cbcb;
}

/* 密码强度指示器 */
.password-strength {
  margin-top: 8px;
}

.strength-indicators {
  display: flex;
  gap: 4px;
  margin-bottom: 4px;
}

.strength-indicator {
  flex: 1;
  height: 4px;
  background-color: #e4e7ed;
  border-radius: 2px;
}

.strength-indicator.weak {
  background-color: #f56c6c;
}

.strength-indicator.medium {
  background-color: #e6a23c;
}

.strength-indicator.strong {
  background-color: #67c23a;
}

.strength-text {
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 767px) {
  .login-wrapper {
    width: 100%;
    height: 100vh;
    max-width: none;
    border-radius: 0;
    box-shadow: none;
  }
  
  .form-section {
    padding: 20px;
  }
  
  .form-content {
    max-width: 100%;
  }
}
</style>